package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.CheckgroupCheckitemKeyMapper;
import com.itheima.dao.HealthGroupMapper;
import com.itheima.dao.HealthItemMapper;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.CheckgroupCheckitemKey;
import org.apache.zookeeper.ZooDefs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;




@Service(interfaceClass = HealthGroupService.class)
public class HealthGroupServiceImpl implements HealthGroupService {

    @Autowired
    private HealthGroupMapper healthGroupMapper;
    @Reference
    private CheckgroupCheckitemKeyService checkgroupCheckitemKeyService;




    @Override
    @Transactional
    public Result AddHealthGroup(CheckGroup checkGroup, long[]ids) {

        boolean b = healthGroupMapper.AddHealthGroup(checkGroup);

        //
        Integer id = checkGroup.getId();



        for (int i=0;i<ids.length-1;i++){

            long checkitemId =ids[i];

            CheckgroupCheckitemKey checkgroupCheckitemKey = new CheckgroupCheckitemKey(id,(int)checkitemId);

           checkgroupCheckitemKeyService.AddCheckjoin(checkgroupCheckitemKey);
        }

        if (!b){
            return new  Result(b, MessageConstant.ADD_CHECKGROUP_FAIL);
        }


        return new Result(b,MessageConstant.ADD_CHECKGROUP_SUCCESS);
    }

    @Override
    @Transactional
    public Result deleteGroup(int id) {

       //查询关联关系
        int i = healthGroupMapper.queryGroupJoin(id);
        //判断关联关系
        if (i>0){
            return new Result(false,MessageConstant.DELETE_CHECKGROUP_FAIL,null);
        }
        //删除关联表数据
        boolean deletejoin = checkgroupCheckitemKeyService.deletejoin(id);



        if (!deletejoin){
            return new Result(false,MessageConstant.DELETE_CHECKGROUP_FAIL,null);
        }
        //删除数据
        boolean b = healthGroupMapper.deleteGroup(id);
        return new  Result(b,MessageConstant.DELETE_CHECKGROUP_SUCCESS);
    }


}
